import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/stores/token.js';

const baseURL = '/api';
const instance = axios.create({ baseURL });

instance.interceptors.request.use(
    (config) => {
        const tokenStore = useTokenStore();
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token;
        }
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

instance.interceptors.response.use(
    result => {
        if (result.data.code === 0) {
            return result.data;
        }
        // ElMessage.error(result.data.msg ? result.data.msg : '服务异常');
        return Promise.reject(result.data);
    },
    async (err) => {
        if (err.response && err.response.status === 401) {
            ElMessage.error('请先登录');
            // 使用动态导入避免循环依赖
            const { default: router } = await import('@/router');
            router.push('/');
        } else {
            ElMessage.error('服务异常');
        }
        return Promise.reject(err);
    }
);

export default instance;
